const express = require('express')
const config = require('./config/index')
const chalk = require('chalk')
const path = require('path')
const cookieParser = require('cookie-parser')
const logger = require('./utils/logger')
const expressSession = require('express-session')
const passport = require('passport')
const cors = require('cors')
const systemRouter = require('./routes/system')
const usersRouter = require('./routes/sys_users')
const projectRouter = require('./routes/project')
const pageRouter = require('./routes/page')
const sourceRouter = require('./routes/source')
const dataAPIRouter = require('./routes/data_api')
const dataSQLRouter = require('./routes/data_sql')
const dataCSVRouter = require('./routes/data_csv')
const dataETLRouter = require('./routes/data_etl')
const chatRouter = require('./routes/chats')
const authRouter = require('./routes/auth')
const process = require("process");
const http = require('http');
const app = express()
const port = config.port
const httpServer = http.createServer(app);

require("./socket_io/index.js")(httpServer);
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(express.json({ limit: '50mb' }));
app.use(cors())
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type');
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  next();
});

app.use(passport.initialize())
app.use((req, res, next) => {
  req.passport = passport // 为了在中间件中可以调用到 passport
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  if (req.method == 'OPTIONS') {
    return res.send(200);
  } else {
    next();
  }
});

require('./utils/passport')(passport)
app.use(logger.netLog())
app.use(expressSession(config.session))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use(authRouter)
app.use(systemRouter)
app.use(usersRouter)
app.use(projectRouter)
app.use(pageRouter)
app.use(sourceRouter)
app.use(dataAPIRouter)
app.use(dataSQLRouter)
app.use(dataCSVRouter)
app.use(dataETLRouter)
app.use(chatRouter)
process.on("uncaughtException", function (err) {
  //打印出错误
  console.log(err);
  //打印出错误的调用栈方便调试
  console.log(err.stack);
});

httpServer.listen(port, err => {
  if (!err) {
    console.log(chalk.blue(`server run success: http://localhost:${port}`))
  } else {
    console.log(chalk.red(err))
  }
})

